<template>
    <div class="user">
        <el-form :inline="true" :model="searchParam" class="demo-form-inline">
            <el-form-item>
                <el-input
                    clearable
                    v-model="searchParam.title"
                    placeholder="商品标题"
                />
            </el-form-item>
            <el-form-item>
                <el-select clearable v-model="searchParam.publishSchoolUuid" placeholder="请选择学校">
                    <el-option v-for="school in data.schools" :key="school.uuid" :label="school.name"
                               :value="school.uuid"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select
                    clearable
                    v-model="searchParam.status"
                    placeholder="请选择状态"
                >
                    <el-option label="待审核" value="1"/>
                    <el-option label="未通过" value="2"/>
                    <el-option label="上架" value="3"/>
                    <el-option label="下架" value="4"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select
                    clearable
                    v-model="searchParam.isSyncLibertySquare"
                    placeholder="是否同步自由广场"
                >
                    <el-option label="同步" value="true"/>
                    <el-option label="未同步" value="false"/>
                </el-select>
            </el-form-item>
            <el-form-item style="width: auto">
                <el-button type="primary" @click="search" size="small">查询</el-button>
                <el-button type="primary" @click="exportCommodityData" size="small">导出商品</el-button>
                <el-button type="warning" @click="batchDropCommodity" size="small">批量下架</el-button>
                <el-button type="success" @click="batchPutCommodity" size="small">批量上架</el-button>
                <el-button type="danger" @click="batchDeleteCommodity" size="small">批量删除</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="data.commodities" border style="width: 100%" v-loading="data.loading"
                  element-loading-text="拼命加载中" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" width="70px"/>
            <el-table-column fixed prop="title" label="商品标题" align="center" width="300px"/>
            <el-table-column prop="originalPrice" label="商品原价" align="center" width="150px">
                <template #default="scope">
                    <span>¥{{ scope.row.originalPrice }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="currentPrice" label="商品现价" align="center" width="150px">
                <template #default="scope">
                    <span>¥{{ scope.row.currentPrice }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="商品分类" align="center" width="150px"/>
            <el-table-column prop="publishNickName" label="发布人" align="center" width="150px"/>
            <el-table-column prop="contactPhone" label="联系电话" align="center" width="150px"/>
            <el-table-column prop="publishSchoolName" label="发布学校" align="center" width="150px"/>
            <el-table-column prop="status" label="状态" align="center" width="150px">
                <template #default="scope">
                    <el-tag
                        v-show="scope.row.status === 1" type="primary"
                        disable-transitions
                    >待审核
                    </el-tag>
                    <el-tag
                        v-show="scope.row.status === 2" type="danger"
                        disable-transitions
                    >未通过
                    </el-tag>
                    <el-tag
                        v-show="scope.row.status === 3" type="success"
                        disable-transitions
                    >上架
                    </el-tag>
                    <el-tag
                        v-show="scope.row.status === 4" type="info"
                        disable-transitions
                    >下架
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="同步自由广场" align="center" width="150px">
                <template #default="scope">
                    <el-tag
                        v-show="scope.row.isSyncLibertySquare" type="success"
                        disable-transitions
                    >同步
                    </el-tag>
                    <el-tag
                        v-show="!scope.row.isSyncLibertySquare" type="primary"
                        disable-transitions
                    >未同步
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间"
                width="180"
                align="center"
            >
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间"
                width="180"
                align="center"
            >
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="300" align="center">
                <template #default="scope">
                    <el-button
                        class="button-space"
                        @click="toExamineCommodity(scope.row.uuid)"
                        v-show="scope.row.status === 1"
                        type="success"
                        size="small"
                    >审核
                    </el-button>
                    <el-button
                        class="button-space"
                        @click="dropCommodity(scope.row.uuid)"
                        v-show="scope.row.status === 3"
                        type="warning"
                        size="small"
                    >下架
                    </el-button>
                    <el-button
                        class="button-space"
                        @click="putCommodity(scope.row.uuid)"
                        v-show="scope.row.status === 4"
                        type="success"
                        size="small"
                    >上架
                    </el-button>
                    <el-button
                        class="button-space"
                        @click="toCommodityDetail(scope.row.uuid)"
                        type="info"
                        size="small"
                    >详情
                    </el-button>
                    <el-popconfirm
                        title="你确定要删除该商品吗？"
                        confirm-button-text="是"
                        cancel-button-text="否"
                        @confirm="deleteCommodity(scope.row.uuid)"
                    >
                        <template #reference>
                            <el-button
                                class="button-space"
                                type="danger"
                                size="small"
                            >删除
                            </el-button>
                        </template>

                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="data.total"
            style="text-align: center; margin-top: 10px"
            @current-change="currentChange"
        >
        </el-pagination>
    </div>
</template>

<script>
import {onMounted, reactive} from "vue";
import {
    page,
    put,
    drop,
    deleted,
    detail,
    noPass,
    pass,
    batchDrop,
    batchPut,
    batchDelete,
    exportCommodity
} from "@/api/commodity/commodity";
import {all} from "@/api/school/school";
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import {useRouter} from "vue-router";
import dayjs from 'dayjs'

export default {
    setup() {
        const searchParam = reactive({
            title: '',
            publishSchoolUuid: '',
            status,
            page: 1,
            size: 10,
            isSyncLibertySquare: ''
        })
        const data = reactive({
            commodities: [],
            total: 0,
            loading: false,
            schools: [],
            commodityExamineDisable: false,
            // 商品详情
            commodityDetail: '',
            commodityDetailDisable: false,
            // 选中的uuid
            selectUuids: []
        })
        const router = useRouter();
        /**
         * 分页查询商品
         * @returns {Promise<void>}
         */
        const pageSearchCommodity = async () => {
            data.loading = true
            page(searchParam).then(res => {
                data.commodities = res.data.records
                data.total = res.data.total
            }).finally(() => {
                data.loading = false
            })
        }

        /**
         * 上架商品
         */
        const putCommodity = async (uuid) => {
            put(uuid).then(() => {
                ElMessage({
                    message: '上架成功',
                    type: 'success',
                })
                pageSearchCommodity()
            })
        }

        /**
         * 下架商品
         */
        const dropCommodity = async (uuid) => {
            drop(uuid).then(() => {
                ElMessage({
                    message: '下架成功',
                    type: 'success',
                })
                pageSearchCommodity()
            })
        }
        /**
         * 删除商品
         * @param uuid
         * @returns {Promise<void>}
         */
        const deleteCommodity = async (uuid) => {
            deleted(uuid).then(() => {
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
                pageSearchCommodity()
            })
        }
        /**
         * 搜索查询商品
         * @returns {Promise<void>}
         */
        const search = async () => {
            page(searchParam).then(res => {
                data.commodities = res.data.records
                data.total = res.data.total
            })
        }

        /**
         * 获取全部学校
         * @returns {Promise<void>}
         */
        const allSchool = async () => {
            all().then(res => {
                data.schools = res.data
            })
        }

        /**
         * 审核商品
         * @param uuid
         * @returns {Promise<void>}
         */
        const viewCommodityExamine = async (uuid) => {
            // 获取商品详情
            detail(uuid).then(res => {
                data.commodityDetail = res.data
            })
            data.commodityExamineDisable = true
        }
        /**
         * 审核不通过
         * @param uuid
         * @returns {Promise<void>}
         */
        const noPassExamine = async (uuid) => {
            noPass(uuid).then(() => {
                ElMessage({
                    message: '审核完成',
                    type: 'success',
                })
                data.commodityExamineDisable = false
                pageSearchCommodity()
            })
        }

        /**
         * 审核通过
         * @param uuid
         * @returns {Promise<void>}
         */
        const passExamine = async (uuid) => {
            pass(uuid).then(() => {
                ElMessage({
                    message: '审核完成',
                    type: 'success',
                })
                data.commodityExamineDisable = false
                pageSearchCommodity()
            })
        }
        /**
         * 去审核页面
         * @param uuid
         */
        const toExamineCommodity = (uuid) => {
            router.push({path: '/commodity/examine', query: {uuid: uuid}})
        }
        /**
         * 去详情页面
         * @param uuid
         */
        const toCommodityDetail = (uuid) => {
            router.push({path: '/commodity/detail', query: {uuid: uuid}})
        }
        /**
         * 商品导出
         */
        const exportCommodityData = () => {
            const loading = ElLoading.service({
                lock: true,
                text: '导出中...',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            exportCommodity(searchParam).then(res => {
                const blob = new Blob([res]);
                const day = dayjs().format('YYYY-MM-DD');
                const fileName = `商品列表${day}.xls`;
                const elink = document.createElement('a');
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
                loading.close()
            })
        }
        /**
         * 批量选中
         * @param selection
         */
        const handleSelectionChange = (selection) => {
            data.selectUuids = selection.map(select => {
                return select.uuid
            })
        }
        /**
         * 批量下架
         */
        const batchDropCommodity = () => {
            if (data.selectUuids.length <= 0) {
                ElMessage({
                    message: '至少选择一个商品',
                    type: 'warning',
                })
                return
            }
            batchDrop(data.selectUuids).then(() => {
                ElMessage({
                    message: '下架成功',
                    type: 'success',
                })
                data.selectUuids = []
                pageSearchCommodity();
            })
        }
        /**
         * 批量上架
         */
        const batchPutCommodity = () => {
            if (data.selectUuids.length <= 0) {
                ElMessage({
                    message: '至少选择一个商品',
                    type: 'warning',
                })
                return
            }
            batchPut(data.selectUuids).then(() => {
                ElMessage({
                    message: '上架成功',
                    type: 'success',
                })
                data.selectUuids = []
                pageSearchCommodity();
            })
        }
        /**
         * 批量删除
         */
        const batchDeleteCommodity = () => {
            if (data.selectUuids.length <= 0) {
                ElMessage({
                    message: '至少选择一个商品',
                    type: 'warning',
                })
                return
            }
            ElMessageBox.confirm(
                '确定要删除所选商品吗?删除后不能恢复',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    batchDelete(data.selectUuids).then(() => {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        data.selectUuids = []
                        pageSearchCommodity();
                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消删除',
                    })
                    data.selectUuids = []
                })
        }
        /**
         * 分页查询
         */
        const currentChange = (value) => {
            searchParam.page = value
            pageSearchCommodity()
        }
        onMounted(() => {
            pageSearchCommodity()
            allSchool()
        })
        return {
            data,
            searchParam,
            putCommodity,
            dropCommodity,
            search,
            deleteCommodity,
            allSchool,
            viewCommodityExamine,
            noPassExamine,
            passExamine,
            toExamineCommodity,
            toCommodityDetail,
            exportCommodityData,
            handleSelectionChange,
            batchDropCommodity,
            batchPutCommodity,
            batchDeleteCommodity,
            currentChange
        }
    }
}
</script>

<style scoped>
.demo-image {
    padding: 30px 0;
    text-align: center;
    display: inline-block;
    width: 20%;
}
</style>